package com.lecoboy.highconcurrency.connectionDemo;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.util.concurrent.TimeUnit;

/**
 * 动态代理构造一个Connection 该Connection的代理实现仅仅是在commit()方法调用时休眠100毫秒
 */
public class ConnectionDriver {
    public final String testName="测试";

    static class ConnectionHandler implements InvocationHandler{

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            if(method.getName().equals("commit")){
               // System.out.println("进入commit休眠100ms");
                TimeUnit.MICROSECONDS.sleep(100);
            }
            return null;
        }
    }

    /**
     * 创建一个connection的代理，在commit时休眠100毫秒
     * @return
     */
    public static final Connection createConnection(){
        return (Connection)Proxy.newProxyInstance(ConnectionDriver.class.getClassLoader(),
                new Class<?>[]{
                        Connection.class
                },
        new ConnectionHandler());
    }
}
